import ajax from '@/uni_modules/u-ajax'
import config from '@/config'
import {
	getToken, removeToken
} from '@/utils/token'

const baseUrl = config.baseUrl

// 创建请求实例
const request = ajax.create({
	baseURL: baseUrl
})

// 请求拦截器
request.interceptors.request.use(
	config => {
		config.header = {
			Authorization: 'Bearer ' + getToken()
		}
		console.log('发送请求', config)
		return config
	},
	error => {
		// 对请求错误做些什么
		console.log('请求错误', error)
		return Promise.reject(error)
	}
)

// 响应拦截器
request.interceptors.response.use(
	response => {
		// 拦截过期用户
		if (response.data.code == 401) {
			console.log('拦截过期用户')
			removeToken()
			uni.showToast({
				title: '未登录或已过期',
				icon: 'error',
				duration: 2000
			})
			uni.reLaunch({
				url: '/pages/login/index'
			})
		} else {
			return response
		}
	},
	error => {
		// 对响应错误做些什么
		console.log('响应错误', error)
		return Promise.reject(error)
	}
)

export default request